/**
 * SysUserAction.java
 * Created at 2016-12-26
 * Created by Administrator
 * Copyright (C) 2016 BROADTEXT SOFTWARE, All rights reserved.
 */
package com.broadtext.rms.system.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.broadtext.common.bean.EntityPageBean;
import com.broadtext.common.exp.DaoException;
import com.broadtext.common.exp.ServiceException;
import com.broadtext.common.utils.MD5Util;
import com.broadtext.common.utils.StringUtils;
import com.broadtext.common.utils.UUIDUtils;
import com.broadtext.rms.system.model.SysAccountValidity;
import com.broadtext.rms.system.model.SysUser;
import com.broadtext.rms.system.model.VSysUsers;
import com.broadtext.rms.system.service.ISysUserService;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds;

/**
 * <p>
 * ClassName: SysUserAction
 * </p>
 * <p>
 * Description: 用户控制层
 * </p>
 * <p>
 * Author: Administrator
 * </p>
 * <p>
 * Date: 2016-12-26
 * </p>
 */
@Controller
@RequestMapping("/main/sysUser")
public class SysUserAction {
    /**
     * 用户Service
     */
    @Autowired
    @Qualifier("sysUserService")
    private ISysUserService sysUserService;

    /**
     * <p>
     * Description: 查询区域信息
     * </p>
     * 
     * @param request 请求对象
     * @param response 返回对象
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    @RequestMapping(value = "/getUser.mvc")
    @ResponseBody
    public void getUser(HttpServletRequest request, HttpServletResponse response) {
        try {
            PageBounds pageBounds;
            pageBounds = new PageBounds();
            Map<String, Object> map;
            String aoData;
            aoData = request.getParameter("aoData");
            JSONArray array;
            array = JSON.parseArray(aoData);
            map = new HashMap<String, Object>();
            if (array != null) {
                Iterator it;
                it = array.iterator();
                while (it.hasNext()) {
                    JSONObject obj;
                    obj = (JSONObject) it.next();
                    if (obj.get("value") != null && !"".equals(obj.get("value") + "")) {
                        map.put(obj.get("name") + "", obj.get("value"));
                    }
                }
            }
           /* //判断当前登录人是否是客户账号，进行数据过滤
            Map<String, Object> checkMap;
            try {
                checkMap = this.sysUserService.checkUserClass(request.getSession().getAttribute("sys.user").toString());
                if(null != checkMap && "true".equals(checkMap.get("flag").toString())){
                    //该用户是客户账号
                    map.put("cusId", checkMap.get("cusId"));
                }
            } catch (DaoException e1) {
                e1.printStackTrace();
            }*/
            pageBounds.setLimit(Integer.parseInt(map.get("iDisplayLength").toString()));
            pageBounds.setPage(Integer.parseInt(map.get("iDisplayStart").toString()) / pageBounds.getLimit() + 1);
            EntityPageBean<VSysUsers> pageBean = this.sysUserService.findUsersPageByQuery(map, pageBounds);
            
            Map dataMap = new HashMap();
            dataMap.put("recordsTotal", pageBean.getiTotalRecords());
            dataMap.put("recordsFiltered", pageBean.getiTotalRecords());
            dataMap.put("aaData", pageBean.getResults());
            dataMap.put("unbindedCount", this.sysUserService.getUnbindCount(map));
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = null;
            try {
                out = response.getWriter();
                out.write(JSON.toJSONString(dataMap));
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (out != null) {
                    out.close();
                }
            }
        } catch (ServiceException e) {
            e.printStackTrace();
        }

    }
    
    /**
     * <p>
     * Description: 查询区域信息
     * </p>
     * 
     * @param request 请求对象
     * @param response 返回对象
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    @RequestMapping(value = "/getUserByCusId.mvc")
    @ResponseBody
    public void getUserByCusId(HttpServletRequest request, HttpServletResponse response) {
        try {
            PageBounds pageBounds;
            pageBounds = new PageBounds();
            Map<String, Object> map;
            String aoData;
            aoData = request.getParameter("aoData");
            JSONArray array;
            array = JSON.parseArray(aoData);
            map = new HashMap<String, Object>();
            if (array != null) {
                Iterator it;
                it = array.iterator();
                while (it.hasNext()) {
                    JSONObject obj;
                    obj = (JSONObject) it.next();
                    if (obj.get("value") != null && !"".equals(obj.get("value") + "")) {
                        map.put(obj.get("name") + "", obj.get("value"));
                    }
                }
            }
            //判断当前登录人是否是客户账号，进行数据过滤
            Map<String, Object> checkMap;
            List<String> ids;
            try {
                checkMap = this.sysUserService.checkUserClass(request.getSession().getAttribute("sys.user").toString());
                if(null != checkMap && "true".equals(checkMap.get("flag").toString())){
                    //该用户是客户账号
                    map.put("cusId", checkMap.get("cusId"));
                    ids = this.sysUserService.findTreeCusIds(checkMap.get("cusId")+"");
                    map.put("ids", ids);
                }
            } catch (DaoException e1) {
                e1.printStackTrace();
            }
            pageBounds.setLimit(Integer.parseInt(map.get("iDisplayLength").toString()));
            pageBounds.setPage(Integer.parseInt(map.get("iDisplayStart").toString()) / pageBounds.getLimit() + 1);
            EntityPageBean<VSysUsers> pageBean = this.sysUserService.findUsersPageByQuery(map, pageBounds);
            Map dataMap = new HashMap();
            dataMap.put("recordsTotal", pageBean.getiTotalRecords());
            dataMap.put("recordsFiltered", pageBean.getiTotalRecords());
            dataMap.put("aaData", pageBean.getResults());
            dataMap.put("unbindedCount", this.sysUserService.getUnbindCount(map));
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = null;
            try {
                out = response.getWriter();
                out.write(JSON.toJSONString(dataMap));
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (out != null) {
                    out.close();
                }
            }
        } catch (ServiceException e) {
            e.printStackTrace();
        }

    }

    /**
     * 
     * <p>Description: 查询用户绑定详情</p>
     * @param request 请求
     * @param response 响应
     * @return 结果
     */
    @RequestMapping(value = "/queryUserBind.mvc")
    @ResponseBody
    public Map<String, Object> queryUserBind(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map;
        map = new HashMap<String, Object>();
        String eId;
        eId = request.getParameter("eId");
      //判断当前登录人是否是客户账号，进行数据过滤
        Map<String, Object> checkMap;
        try {
            checkMap = this.sysUserService.checkUserClass(request.getSession().getAttribute("sys.user").toString());
            if(null != checkMap && "true".equals(checkMap.get("flag").toString())){
                //该用户是客户账号
                Map<String, Object> roleMap = this.sysUserService.getCustomerRole();
                if(map!=null){
                    map.put("roleId", roleMap.get("dict_key"));
                    map.put("rname", roleMap.get("dict_value"));
                }
                map.put("flag",true);
            }
            map.put("data", this.sysUserService.getUserBindInfo(eId));
        } catch (DaoException e1) {
            e1.printStackTrace();
        } catch (ServiceException e) {
            e.printStackTrace();
        }
        return map;
    }
    
    /**
     * 
     * <p>Description: 查询用户绑定详情</p>
     * @param request 请求
     * @param response 响应
     * @return 结果
     */
    @RequestMapping(value = "/queryAccountValidityInfo.mvc")
    @ResponseBody
    public Map<String, Object> queryAccountValidityInfo(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map;
        map = new HashMap<String, Object>();
        String eId;
        eId = request.getParameter("eId");
        try {
            map.put("data", this.sysUserService.getAccountValidityInfo(eId));
        } catch (ServiceException e) {
            e.printStackTrace();
        }
        return map;
    }
    
    /**
     * 
     * <p>Description: 绑定或更新绑定用户</p>
     * @param request 请求
     * @param user 用户
     * @return 保存结果
     */
    @RequestMapping(value = "/saveOrUpdateBindUser.mvc")
    @ResponseBody
    public Map<String, Object> saveOrUpdateBindUser (HttpServletRequest request, SysUser user) {
        Map<String, Object> map;
        map = new HashMap<String, Object>();
        String sysUser;
        sysUser = String.valueOf(request.getSession().getAttribute("sys.userName"));
        try { 
            if ("".equals(user.getPkId())) {
                //add
                user.setPkId(null);
                if (this.sysUserService.checkUserNameOk(user)) {
                    //新绑定用户密码需转码
                    user.setPass(MD5Util.getDigest(user.getPass()));
                    user.setDelFlag("0");
                    String userId = UUIDUtils.getUUID();
                    user.setPkId(userId);
                    user.setCreateUser(sysUser);
                    Date creatadDate = new Date();
                    user.setCreateDate(creatadDate);
                    user.setUpdateUser(sysUser);
                    user.setUpdateDate(new Date());
                    boolean flag = this.sysUserService.insertRecord(user);
                    //保存用户角色，当客户为下级单位客户绑定账号的时候绑定默认客户角色
                    if(StringUtils.isNotBlank(user.getRoleId())){
                        this.sysUserService.saveUserRole(userId,user.getRoleId());
                    }
                    map.put("msg", flag);
                    //账号绑定成功，则生成账户使用期限记录
                    if (flag) {
                        SysAccountValidity account = new SysAccountValidity();
                        account.setPkId(UUIDUtils.getUUID());
                        account.setUserId(user.getUserId());
                        account.setLoginName(user.getLoginName());
                        account.setAccountStartDate(creatadDate);
                        //账户初始使用期限类型 永久
                        account.setAccountValidity("0");
                        account.setAccountEndDate(null);
                        
                        account.setCreateUser(sysUser);
                        account.setCreateDate(new Date());
                        account.setUpdateUser(sysUser);
                        account.setUpdateDate(new Date());
                        account.setDelFlag("0");
                        this.sysUserService.saveAccountValidityInfo(account);
                    }
                } else {
                    map.put("msg", "repeat");
                }
            } else {
                //update
                if (this.sysUserService.checkUserNameOk(user)) {
                    SysUser bindUser;
                    bindUser = this.sysUserService.findEntityById(user.getPkId());
                    //验证当前操作用户是否有效
                    if (bindUser != null) {
                        if (!user.getPass().equals(bindUser.getPass())) {
                            //密码有变更
                            user.setPass(MD5Util.getDigest(user.getPass()));
                        }
                        user.setUpdateDate(new Date());
                        user.setUpdateUser(sysUser);
                        try {
                            boolean flag = this.sysUserService.updateRecord(user);
                            map.put("msg", flag);
                            //更新成功，修改账户期限信息表中的信息
                            if(flag){
                                SysAccountValidity account = new SysAccountValidity(); 
                                account.setUserId(user.getUserId());
                                account.setLoginName(user.getLoginName());
                                account.setUpdateUser(sysUser);
                                account.setUpdateDate(new Date());
                                this.sysUserService.updateAccountValidityByEId(account);
                            }
                        } catch (ServiceException e) {
                            e.printStackTrace();
                        }
                    } else {
                        map.put("msg", "error");
                    }
                } else {
                    map.put("msg", "repeat");
                }
            }
        } catch (ServiceException e) {
            e.printStackTrace();
        }
        return map;
    }
    
    
    /**
     * 
     * <p>Description: 绑定或更新绑定用户</p>
     * @param request 请求
     * @param user 用户
     * @return 保存结果
     */
    @RequestMapping(value = "/saveOrUpdateValidityInfo.mvc")
    @ResponseBody
    public Map<String,Object> saveOrUpdateValidityInfo(HttpServletRequest request, SysAccountValidity user) throws Exception{
        Map<String, Object> map;
        map = new HashMap<String, Object>();
        String sysUser;
        sysUser = String.valueOf(request.getSession().getAttribute("sys.userName"));
        if(StringUtils.isBlank(user.getPkId())){
            user.setDelFlag("0");
            user.setPkId(UUIDUtils.getUUID());
            user.setCreateUser(sysUser);
            user.setCreateDate(new Date());
            user.setUpdateUser(sysUser);
            user.setUpdateDate(new Date());
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if(StringUtils.isNotBlank(user.getAccountStartDateStr())){
                Date dateStart = format.parse(user.getAccountStartDateStr());
                user.setAccountStartDate(dateStart);
            }
            if(StringUtils.isNotBlank(user.getAccountEndDateStr())){
                Date dateEnd = format.parse(user.getAccountEndDateStr());
                user.setAccountEndDate(dateEnd);
            }
            map.put("msg", this.sysUserService.saveAccountValidityInfo(user));
        }else {
            user.setUpdateDate(new Date());
            user.setUpdateUser(sysUser);
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if(StringUtils.isNotBlank(user.getAccountStartDateStr())){
                Date dateStart = format.parse(user.getAccountStartDateStr());
                user.setAccountStartDate(dateStart);
            }
            if(StringUtils.isNotBlank(user.getAccountEndDateStr())){
                Date dateEnd = format.parse(user.getAccountEndDateStr());
                user.setAccountEndDate(dateEnd);
            }else {
                user.setAccountEndDate(null);
            }
            map.put("msg", this.sysUserService.updateAccountValidityInfo(user));
        }
        return map;
    }
    
    /**
     * 
     * <p>Description: 取消绑定</p>
     * @param request 请求
     * @param response 响应
     * @return 操作结果
     */
    @RequestMapping(value = "/cancelUserBind.mvc")
    @ResponseBody
    public Map<String, Object> cancelUserBind (HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map;
        map = new HashMap<String, Object>();
        String sysUser;
        sysUser = String.valueOf(request.getSession().getAttribute("sys.userName"));
        String ids;
        ids = request.getParameter("userId");
        String[] idArray;
        idArray = ids.split(",");
        try {
            map.put("msg", this.sysUserService.cancelUserBind(idArray, sysUser));
        } catch (ServiceException e) {
            e.printStackTrace();
        }
        return map;
    }
    
    /**
     * 
     * <p>Description: 账户锁定</p>
     * @param request 请求
     * @param response 响应
     * @return 操作结果
     */
    @RequestMapping(value = "/lockUser.mvc")
    @ResponseBody
    public Map<String, Object> lockUser (HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map;
        map = new HashMap<String, Object>();
        String sysUser;
        sysUser = String.valueOf(request.getSession().getAttribute("sys.userName"));
        String ids;
        ids = request.getParameter("userId");
        String[] idArray;
        idArray = ids.split(",");
        try {
            map.put("msg", this.sysUserService.lockUser(sysUser, idArray));
        } catch (ServiceException e) {
            e.printStackTrace();
        }
        return map;
    }
    
    /**
     * 
     * <p>Description: 账户解除锁定</p>
     * @param request 请求
     * @param response 响应
     * @return 操作结果
     */
    @RequestMapping(value = "/lockCancel.mvc")
    @ResponseBody
    public Map<String, Object> lockCancel (HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map;
        map = new HashMap<String, Object>();
        String sysUser;
        sysUser = String.valueOf(request.getSession().getAttribute("sys.userName"));
        String ids;
        ids = request.getParameter("userId");
        String[] idArray;
        idArray = ids.split(",");
        try {
            map.put("msg", this.sysUserService.lockCancel(sysUser, idArray));
        } catch (ServiceException e) {
            e.printStackTrace();
        }
        return map;
    }
    
    
    @RequestMapping(value = "/getRoleOptions.mvc")
    @ResponseBody
    public Map<String, Object> getRoleOptions(HttpServletRequest request)  {
        Map<String, Object> map = new HashMap<String, Object>();
        //判断当前登录人是否是客户账号，进行数据过滤
        Map<String, Object> checkMap;
        List<Object> list;
        try {
            checkMap = this.sysUserService.checkUserClass(request.getSession().getAttribute("sys.user").toString());
            if(null != checkMap && "true".equals(checkMap.get("flag").toString())){
                //该用户是客户账号
                list = this.sysUserService.getRoleOptions(String.valueOf(checkMap.get("cusId")));
            }else {
                list = this.sysUserService.getRoleOptions(null);
            }
            map.put("dict", list);
        } catch (ServiceException e) {
            e.printStackTrace();
        } catch (DaoException e1) {
            e1.printStackTrace();
        } 
        return map;
    }
    
    
    /**
     * 
     * <p>Description: 检查当前登录人账号类类型</p>
     * @param request 请求
     */
    @RequestMapping(value = "/checkUserClass.mvc")
    @ResponseBody
    public Object checkUserClass(HttpServletRequest request) {
        try {
            return this.sysUserService.checkUserClass(request.getSession().getAttribute("sys.user").toString());
        } catch (DaoException e) {
            e.printStackTrace();
        }
        return null;
    }
}
